<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

function postXmlSSLCurl($xml, $url, $second, $cert, $key)
{
    $ch = curl_init();
    //超时时间
//    curl_setopt($ch,CURLOPT_TIMEOUT,$second ? $second : $this->timeout);

    //这里设置代理，如果有的话
    //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
    //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
    //设置header
    curl_setopt($ch,CURLOPT_HEADER,FALSE);
    //要求结果为字符串且输出到屏幕上
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
    //设置证书
    //使用证书：cert 与 key 分别属于两个.pem文件
    //默认格式为PEM，可以注释
    curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
    curl_setopt($ch,CURLOPT_SSLCERT,$cert);
    //默认格式为PEM，可以注释
    curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
    curl_setopt($ch,CURLOPT_SSLKEY, $key);
    //post提交方式
    curl_setopt($ch,CURLOPT_POST, true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
    $data = curl_exec($ch);

    //返回结果
    if($data){
        curl_close($ch);
        return  xmlToArray($data);
    }
    else {
        $error = curl_errno($ch);
        echo "curl出错，错误码:$error"."<br>";
        curl_close($ch);
        return false;
    }
}


//将XML转为array
function xmlToArray($xml)
{
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}

//数组转XML
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key=>$val)
    {
        if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    return $xml;
}




function complem_number($num =1)
{
    //自动补全编号
    $temp_num = 100000001;
    $new_num = $num + $temp_num;
    $real_num =substr($new_num,1,8); //即截取掉最前面的“1”
    return $real_num;
}

function add_material($url,$imgurl){
    $file_path = $imgurl;

    $file_data = array('media'  => '@'.$file_path);
   // $file_data = array("media"  =>  new CURLFile($file_path));
    $file_data = array("media"  =>  new CURLFile($file_path));
    $ch = curl_init();
    curl_setopt($ch , CURLOPT_URL , $url);
    //需要获取的URL地址，也可以在curl_init()函数中设置。
    curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
    //使用PHP curl获取页面内容或提交数据，有时候希望返回的内容作为变量储存，
    //而不是直接输出。这个时候就必需设置curl的CURLOPT_RETURNTRANSFER选项为1或true
    curl_setopt($ch , CURLOPT_POST, 1);
    //发送一个POST请求
    curl_setopt($ch , CURLOPT_POSTFIELDS, $file_data);
    //传递一个关联数组，生成multipart/form-data的POST请求
    $output = curl_exec($ch);//发送请求获取结果
    curl_close($ch);//关闭会话
    return $output;//返回结果
}
function  user_no($user_no){
    return    str_pad($user_no,6,"0",STR_PAD_LEFT  );
}

/**
 * 生成订单号
 * @author hejianyu
 */
function orderNum()
{
    // return  chr(rand(65, 90)) . date('YmdHis', time()) . numberCaptcha(4);
    return chr(rand(65, 90)) . date('YmdHis', time()) . chr(rand(65, 90));
}

function check_card($idcard,$name)
{
    //d1299ffb9ceb1f5efa07517dab177908
    //6f74145cbd7989a4f216b51ee25dfd98
    $url = 'http://op.juhe.cn/idcard/query?key=6f74145cbd7989a4f216b51ee25dfd98&idcard=' . $idcard . '&realname=' . urlencode($name);
    $http_info = http_curl($url, 'get');

    $msg = '';
    if($http_info['error_code'] == 0){
        return 1;
    }else{
        switch ($http_info['error_code']) {
            case '210301':
                $msg = "库中无此身份证记录";
                break;
            case '210302':
                $msg = "第三方服务器异常";
                break;
            case '210303':
                $msg = "服务器维护";
                break;
            case '210304':
                $msg = "姓名或身份证格式错误或请求次数过于频繁";
                break;
            case '210305':
                $msg = "网络错误，请重试";
                break;
            case '210306':
                $msg = "数据源错误，具体参照reason";
                break;
            case '210307':
                $msg = "sign错误";
                break;
            case '112':
                $msg = "身份证请求查询次数不足";
                break;
          }
        return $msg;
    }

}





//下载文件
function download_file($file)
{
    if (is_file($file)) {
        $length = filesize($file);
        $type = mime_content_type($file);
        $showname = ltrim(strrchr($file, '/'), '/');

        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
            header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $showname . '"');
        }
        readfile($file);
        exit;
    } else {
        exit('文件已被删除！');
    }
}
/**
 * 生成二维码 方法
 */
function qr_code($url){
    //引入vendor 下phpqrcode 文件
    vendor('phpqrcode.phpqrcode');

    $filename=uniqid().'.png';
    $path='qrcode/'.date('Ymd',time()).'/';

    //创建文件
    if(!file_exists($path)){
        mkdir($path,0777,true);//创建目录
        chmod($path,0777);//赋予权限
    }
    $filepath=$path.$filename;

    $errorCorrectionLevel='L';//纠错级别 :L,M,Q,H
    $matrixPointSize="5";     //生成图片大小 :1到10
    QRcode::png($url,$filepath,$errorCorrectionLevel,$matrixPointSize,2);

    return  config('server_url').'/'.$filepath;
    exit();
}




/*
 *  生成信息二维码
 */
function get_video_code($type, $id = '')
{

    // $type  1 视频  2 个人信息
    if ($type == 1) {
        $path = 'pages/index/index';
    } else if ($type == 2) {
        $path = 'pages/index/index';
    }
//        '?video_id='.$id
    //实例化数据库
    $token = $this->token();
    //获取 二维码
    $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $token;
    //跳转页面
    $data = array(
        'path' => $path
    );
    $code = json_encode($data);
    $imgInfo = $this->api_notice_increment($url, $code);
    $local = 'static/Code/' . date('YmdHis') . rand(1221212, 1212012102102) . '.png';
    file_put_contents($local, $imgInfo);
    sleep(3);
    $code_url = $this->upImg($local);
    print_t($code_url);
    if ($type == 2) {
        // 直接存 用户表
        $data['code_url'] = $code_url;
        $user_identity_info = new user_identity_info();
        $user_identity_info->allowField(true)->save($data, ['id' => $id]);
    } else if ($type == 1) {
        return $code_url;
    }

}

/**
 * 维护token
 */
function token()
{    //实例化数据库
    $wxtoken = Db('wx_token');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . config('xiaocx_app_id') . "&secret=" . config('xiaocx_app_secret');
    //查询
    $infoList = $wxtoken->limit(1)->find();
    $oldtime = strtotime($infoList['updatetime']);
    $newtime = time();
    $time = $newtime - $oldtime;
    if ($infoList) {
        if ($time > 5000) {
            $info = http_curl($url, 'get');
            if (!$info) {
                json_fail('获取token失败');
            }
            //更新的数据
            $data = array(
                'wxatid' => $infoList['wxatid'],
                'access_token' => $info['access_token'],
                'expires_in' => $info['expires_in'],
                'updatetime' => date('Y-m-d H:i:s')
            );
            $wxtoken->update($data);
            return $info['access_token'];
        } else {
            return $infoList['access_token'];
        }
    } else {
        $info = http_curl($url, 'get');
        //添加的数据
        $data = array(
            'access_token' => $info['access_token'],
            'expires_in' => $info['expires_in'],
            'createtime' => date('Y-m-d H:i:s'),
            'updatetime' => date('Y-m-d H:i:s')
        );
        $wxtoken->insertGetId($data);
        return $infoList['access_token'];
    }
}



/**
 * @param $url 网址
 * @param $filename 保存文件名
 * @param int $timeout 过期时间
 * @return bool
 * 下载远程文件
 */
function http_down($url, $filename, $timeout = 60)
{
    $path = dirname($filename);
    if (!is_dir($path) && !mkdir($path, 0755, true)) {
        return false;
    }
    $fp = fopen($filename, 'w');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    return $filename;
}

/**
 * excel表格导出
 * @param string $fileName 文件名称
 * @param array $headArr 表头名称
 * @param array $data 要导出的数据
 * @author Eric
 */

function excelExport($fileName = '', $headArr = [], $data = [])
{

    $fileName .= date("Y_m_d_H_i", time()) . rand(1, 100) . ".xlsx";
    vendor("phpexcel.PHPExcel"); //方法一
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->getProperties();
    $key = ord("A"); // 设置表头

    foreach ($headArr as $v) {
        $colum = chr($key);
        $objPHPExcel->getActiveSheet()->getColumnDimension($colum)->setWidth(20);
        $objPHPExcel->getActiveSheet()->getStyle($colum)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle($colum)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach ($data as $key => $rows) { // 行写入
        set_time_limit(0);
        $span = ord("A");
        foreach ($rows as $keyName => $value) { // 列写入
            set_time_limit(0);
            $objActSheet->setCellValue(chr($span) . $column, $value);
            $span++;
        }
        $column++;
    }
    $fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
    $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename='$fileName'");
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output'); // 文件通过浏览器下载
    exit();
}

function data($num, $val)
{
    return array(
        'status' => $num,
        'msg' => $val
    );
}

//判断两个字符串是否相等
function trie_mall($new, $str)
{
    $oldchar = array(" ", "　", "\t", "\n", "\r");
    $newchar = array("", "", "", "", "");
    $new_str = str_replace($oldchar, $newchar, $str);
    if ($new === $new_str) {
        return 1;
    } else {
        return 2;
    }
}

/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key 加密密钥
 * @param int $expire 过期时间 单位 秒
 * return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function encode($data, $key = '', $expire = 0)
{
    $key = md5(empty($key) ? 'SRWERWE1232' : $key);
    $data = base64_encode($data);
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time() : 0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }
    return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key 加密密钥
 * return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function decode($data, $key = '')
{
    $key = md5(empty($key) ? 'SRWERWE1232' : $key);
    $data = str_replace(array('-', '_'), array('+', '/'), $data);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data = substr($data, 10);
    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}

/**
 * 数字验证码
 * @author hejianyu
 */
function numberCaptcha($length = 4)
{
    (int)$min = substr(10000000000, 0, $length);
    (int)$max = substr(99999999999, 0, $length);
    return rand($min, $max);
}

/**
 * 格式化打印数组
 * @param $arr
 * @author zhengjingqiang
 * @email scenewood@163.com
 */
function print_t($arr)
{
    echo '<pre>';
    print_r($arr);
    echo '</pre><hr/>';
    exit;
}

//微信用户名解密
function urlsafe_b64decode($string)
{
    $data = str_replace(array('-', '_'), array('+', '/'), $string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

//微信用户名加密
function urlsafe_b64encode($string)
{
    $data = base64_encode($string);
    $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
    return $data;
}

function dd($arr)
{
    print_t($arr);
}

/***** 身份证验证*******/
function validation_filter_id_card($id_card)
{
    if (strlen($id_card) == 18) {
        return idcard_checksum18($id_card);
    } elseif ((strlen($id_card) == 15)) {
        $id_card = idcard_15to18($id_card);
        return idcard_checksum18($id_card);
    } else {
        return false;
    }
}

// 计算身份证校验码，根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base)
{
    if (strlen($idcard_base) != 17) {
        return false;
    }
    //加权因子
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    //校验码对应值
    $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    $checksum = 0;
    for ($i = 0; $i < strlen($idcard_base); $i++) {
        $checksum += substr($idcard_base, $i, 1) * $factor[$i];
    }
    $mod = $checksum % 11;
    $verify_number = $verify_number_list[$mod];
    return $verify_number;
}

// 将15位身份证升级到18位
function idcard_15to18($idcard)
{
    if (strlen($idcard) != 15) {
        return false;
    } else {
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false) {
            $idcard = substr($idcard, 0, 6) . '18' . substr($idcard, 6, 9);
        } else {
            $idcard = substr($idcard, 0, 6) . '19' . substr($idcard, 6, 9);
        }
    }
    $idcard = $idcard . idcard_verify_number($idcard);
    return $idcard;
}


// 18位身份证校验码有效性检查
function idcard_checksum18($idcard)
{
    if (strlen($idcard) != 18) {
        return false;
    }
    $idcard_base = substr($idcard, 0, 17);
    if (idcard_verify_number($idcard_base) != strtoupper(substr($idcard, 17, 1))) {
        return false;
    } else {
        return true;
    }
}

/***** 身份证验证结束*******/


/**
 * 无限分类
 * @param $array
 * @param int $pid
 * @return array
 * @author zhengjingqiang
 * @email scenewood@163.com
 */
function menuTree($array, $pid)
{
    $arr = array();
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $tem = menuTree($array, $v['id']);
//            if($v['parameter'] && $v['url']){
//                $params = json_decode($v['parameter'], true);
//                $v['urlStr'] = URL($v['url'], $params);
//            } elseif($v['url']) {
//                $v['urlStr'] = URL($v['url']);
//            }
            //判断是否存在子数组
            $tem && $v['child'] = $tem;
            $arr[] = $v;
        }
    }
    return $arr;
}


/***** 生成二维码*******/
function getQrcode($id, $type)
{
    $EarlyRise = D('EarlyRise');
    $info = $EarlyRise->field('title,id,picture,content')->find($id);
    $info['content'] = strip_tags(htmlspecialchars_decode($info['content']));
    return $info;
}


/**
 * 密码加密
 * @author hejianyu
 */
function encryption($str)
{
    $result = sha1(sha1($str, true));
    return $result;
}

function Allerror()
{
    return $arr = array('errorCode' => '10000', 'msg' => '获取参数错误');
}


/**
 * 注册IP
 * @author hejianyu
 */
function registerIp()
{
    $registerIp = get_client_ip();
    return $registerIp;
}


/**
 * 遍历获取目录下的指定类型的文件
 * @param $path      目录地址
 * @param array $files
 * @return array
 * @author jihaichuan
 * @date 2015-10-16
 */
function getfiles($path, $allowFiles, &$files = array())
{
    if (!is_dir($path)) return null;
    if (substr($path, strlen($path) - 1) != '/') $path .= '/';
    $handle = opendir($path);
    while (false !== ($file = readdir($handle))) {
        if ($file != '.' && $file != '..') {
            $path2 = $path . $file;
            if (is_dir($path2)) {
                getfiles($path2, $allowFiles, $files);
            } else {
                if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
                    $files[] = array(
                        'url' => substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                        'mtime' => filemtime($path2)
                    );
                }
            }
        }
    }
    return $files;
}


/**
 * 无限分类
 * @param $array
 * @param int $pid
 * @return array
 */
function tree($array, $pid = 0)
{
    $arr = array();
    $tem = array();
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            if (isset($v['url'])) {
                $parameter = array();
                if ($v['parameter']) {
                    $parameter = json_decode($v['parameter'], true);
                }
                $v['url'] = URL($v['url'], $parameter);
            }
            $tem = tree($array, $v['id']);
            //判断是否存在子数组
            $tem && $v['children'] = $tem;
            $arr[] = $v;
        }
    }
    return $arr;
}


/**
 * 到期时间
 * @author jihaichuan
 */
function expirationTime()
{
    return time() + 60 * 10;
}


/**
 * 将邮箱中间部分转换成*
 * @param $email 邮箱
 * @return mixed
 * @author hejianyu
 */
function hideEmail($email)
{
    $n = strpos($email, '@');
    if ($n < 3) {
        $info = substr_replace($email, "****", $n, 0);
    } elseif ($n < 6) {
        $info = substr_replace($email, "****", 2, $n - 2);
    } else {
        $info = substr_replace($email, "****", 2, $n - 4);
    }
    return $info;
}


/**
 * 格式化金额
 * @param $price
 * @return float|string
 * @author jihaichuan
 */
function formatAmount($price)
{
    if (!$price) return '0.00';
    return number_format($price / 100, 2);
}


/** 将字符串转换成数组
 * @param string $str
 * @return array
 * @author jihaichuan
 */
function nl2brStrArr($str = '')
{
    $listArr = explode('<br />', nl2br($str));
    $listArray = array();
    if ($listArr) {
        foreach ($listArr as $k => $v) {
            if ($v) {
                $listArray[] = $v;
            }
        }
    }
    return $listArray;
}


/**
 * 签名字符串
 * @param $prestr 需要签名的字符串
 * @param $key 私钥
 * return 签名结果
 */
function md5Sign($prestr, $key)
{
    $prestr = $prestr . $key;
    return md5($prestr);
}

/**
 * 验证签名
 * @param $prestr 需要签名的字符串
 * @param $sign 签名结果
 * @param $key 私钥
 * return 签名结果
 */
function md5Verify($prestr, $sign, $key)
{
    $prestr = $prestr . $key;
    $mysgin = md5($prestr);

    if ($mysgin == $sign) {
        return true;
    } else {
        return false;
    }
}


/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstring($para)
{
    $arg = "";
    while (list ($key, $val) = each($para)) {
        $arg .= $key . "=" . $val . "&";
    }
    //去掉最后一个&字符
    $arg = substr($arg, 0, count($arg) - 2);

    //如果存在转义字符，那么去掉转义
    if (get_magic_quotes_gpc()) {
        $arg = stripslashes($arg);
    }

    return $arg;
}

/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做urlencode编码
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstringUrlencode($para)
{
    $arg = "";
    while (list ($key, $val) = each($para)) {
        $arg .= $key . "=" . urlencode($val) . "&";
    }
    //去掉最后一个&字符
    $arg = substr($arg, 0, count($arg) - 2);

    //如果存在转义字符，那么去掉转义
    if (get_magic_quotes_gpc()) {
        $arg = stripslashes($arg);
    }

    return $arg;
}

/**
 * 除去数组中的空值和签名参数
 * @param $para 签名参数组
 * return 去掉空值与签名参数后的新签名参数组
 */
function paraFilter($para)
{
    $para_filter = array();
    while (list ($key, $val) = each($para)) {
        if ($key == "sign" || $key == "sign_type" || $val == "") continue;
        else    $para_filter[$key] = $para[$key];
    }
    return $para_filter;
}

/**
 * 对数组排序
 * @param $para 排序前的数组
 * return 排序后的数组
 */
function argSort($para)
{
    ksort($para);
    reset($para);
    return $para;
}

/**
 * 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
 * 注意：服务器需要开通fopen配置
 * @param $word 要写入日志里的文本内容 默认值：空值
 */
function logResult($word = '')
{
    $fp = fopen("log.txt", "a");
    flock($fp, LOCK_EX);
    fwrite($fp, "执行日期：" . strftime("%Y%m%d%H%M%S", time()) . "\n" . $word . "\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

/**
 * 远程获取数据，POST模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * @param $para 请求的数据
 * @param $input_charset 编码格式。默认值：空值
 * return 远程输出的数据
 */
function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '')
{

    if (trim($input_charset) != '') {
        $url = $url . "_input_charset=" . $input_charset;
    }
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
    curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
    curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
    curl_setopt($curl, CURLOPT_POST, true); // post传输数据
    curl_setopt($curl, CURLOPT_POSTFIELDS, $para);// post传输数据
    $responseText = curl_exec($curl);
    //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
    curl_close($curl);

    return $responseText;
}

/**
 * 远程获取数据，GET模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * return 远程输出的数据
 */
function getHttpResponseGET($url, $cacert_url)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
    curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
    $responseText = curl_exec($curl);
    //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
    curl_close($curl);

    return $responseText;
}

/**
 * 实现多种字符编码方式
 * @param $input 需要编码的字符串
 * @param $_output_charset 输出的编码格式
 * @param $_input_charset 输入的编码格式
 * return 编码后的字符串
 */
function charsetEncode($input, $_output_charset, $_input_charset)
{
    $output = "";
    if (!isset($_output_charset)) $_output_charset = $_input_charset;
    if ($_input_charset == $_output_charset || $input == null) {
        $output = $input;
    } elseif (function_exists("mb_convert_encoding")) {
        $output = mb_convert_encoding($input, $_output_charset, $_input_charset);
    } elseif (function_exists("iconv")) {
        $output = iconv($_input_charset, $_output_charset, $input);
    } else die("sorry, you have no libs support for charset change.");
    return $output;
}

/**
 * 实现多种字符解码方式
 * @param $input 需要解码的字符串
 * @param $_output_charset 输出的解码格式
 * @param $_input_charset 输入的解码格式
 * return 解码后的字符串
 */
function charsetDecode($input, $_input_charset, $_output_charset)
{
    $output = "";
    if (!isset($_input_charset)) $_input_charset = $_input_charset;
    if ($_input_charset == $_output_charset || $input == null) {
        $output = $input;
    } elseif (function_exists("mb_convert_encoding")) {
        $output = mb_convert_encoding($input, $_output_charset, $_input_charset);
    } elseif (function_exists("iconv")) {
        $output = iconv($_input_charset, $_output_charset, $input);
    } else die("sorry, you have no libs support for charset changes.");
    return $output;
}


/**
 * 截取字符串
 * @param string $str // 字符串
 * @param int $start // 开始截取位置
 * @param int $end // 结束截取的位置
 * @return string       // 返回截取后的字符串
 * @author jihaichuan
 */
function cutStr($str = '', $start = 0, $end = 10)
{
    if ($str) {
        $count = strlen($str);
        if ($count > $end) {
            $str = mb_strcut($str, $start, $end, 'utf-8') . '...';
        }
        return $str;
    }
}


/**
 * 获取ip地址接口
 * @param string $ip
 * @param string $coor
 * @return mixed
 * @author jihaichuan
 */
function getIpApi($ip = '', $coor = '')
{
    if (!$ip) {
        $ip = get_client_ip();
    }
    // 初始化CURL
    $ch = curl_init();
    $url = 'http://apis.baidu.com/apistore/iplookupservice/iplookup?ip=' . $ip;
    $header = array(
        'apikey: ac25999eb56d018d9b8ae215d8b17af9',
    );
    // 添加apikey到header
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 执行HTTP请求
    curl_setopt($ch, CURLOPT_URL, $url);
    $res = curl_exec($ch);

    return json_decode($res, true);
}


/**
 * 快递接口
 * @param $com // 物流公司编号，对于数据库表中数据
 * @param $sn // 物流单号
 * @return mixed
 * @author jihaichuan
 */
function getExpressApi($com, $sn)
{
    $ch = curl_init();
    $url = 'http://v.juhe.cn/exp/index?key=52683939544112da0c8d2a8010ddc573&com=' . $com . '&no=' . $sn;

    // 添加apikey到header
    curl_setopt($ch, CURLOPT_HTTPHEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // 执行HTTP请求
    curl_setopt($ch, CURLOPT_URL, $url);
    $res = curl_exec($ch);

    return json_decode($res, true);
}


/**
 * 快递100-生成查询快递iFrame标签内容的URL地址
 * @param $com // 快递公司编号
 * @param $sn // 快递单号
 * @author jihaichuan
 */
function buildExpressUrl($com, $sn)
{
    // 快递100公司编号
    $name = '';
    switch ($com) {
        case 'sf':
            $name = 'shunfeng';
            break;
        case 'sto':
            $name = 'shentong';
            break;
        case 'zto':
            $name = 'zhongtong';
            break;
        default:
            $name = 'shunfeng';
            break;
    }

    // 组合URL地址
    return 'http://www.kuaidi100.com/chaxun?com=' . $name . '&nu=' . $sn;
}


/**
 * 剩余时间
 * @param timer $
 * @return mixed
 * @author jihaichuan
 */
function remainingTime($timer)
{
    $timeArr = array();
    // 判断天数
    if ($timer >= 86400) {
        $timeArr['day'] = intval($timer / 86400);
        if ($timeArr['day'] < 10) {
            $timeArr['day'] = '0' . $timeArr['day'];
        }
        $timer = ($timer % 86400);
    } else {
        $timeArr['day'] = '00';
    }
    // 判断小时
    if ($timer < 86400 && $timer >= 3600) {
        $timeArr['hour'] = intval($timer / 3600);
        if ($timeArr['hour'] < 10) {
            $timeArr['hour'] = '0' . $timeArr['hour'];
        }
        $timer = ($timer % 3600);
    } else {
        $timeArr['hour'] = '00';
    }
    // 判断分钟
    if ($timer < 3600 && $timer > 60) {
        $timeArr['minute'] = intval($timer / 60);
        if ($timeArr['minute'] < 10) {
            $timeArr['minute'] = '0' . $timeArr['minute'];
        }
        $timer = ($timer % 60);
    } else {
        $timeArr['minute'] = '00';
    }
    // 判断秒
    if ($timer < 60 && $timer >= 1) {
        $timeArr['second'] = $timer;
        if ($timeArr['second'] < 10) {
            $timeArr['second'] = '0' . $timeArr['second'];
        }
    } else {
        $timeArr['second'] = '00';
    }
    return $timeArr;
}


/**
 * 字符串替换星号方法
 * @param String $str 要替换的字符串
 * @param Integer $start 前面保留几位
 * @param Integer $middle 中间替换几位
 * @param Integer $end 最后保留几位
 */
function starStrConvert($str, $start, $middle, $end)
{
    $pattern = "/(\w{" . $start . "})(\w{" . $middle . "})(\w{" . $end . "})/";
    $replacement = '$1****$3';
    $str = preg_replace($pattern, $replacement, $str);
    return $str;
}


/**
 * 生成用户昵称
 * @param $mobile 手机号码后六位
 * @param int $n 重复时数字后缀
 * @return string
 * @author hejianyu
 */
function createNickname($mobile, $n = 0)
{
    $name = '台球圈';
    $nickname = $name . $mobile;

    if ($n != 0) {
        $nickname = $nickname . $n;
    }

    //昵称是否被使用
    $info = R('Api/Member/isNickname', array('name' => $nickname));
    if ($info) {
        return createNickname($mobile, $n + 1);
    } else {
        return $nickname;
    }
}


/**
 * 转换成小时分钟
 * @param array $arr
 * @author hejianyu
 */
function Msec2Time($msec)
{
    if (is_numeric($msec)) {
        $sec = abs(ceil(($msec - time())));
        $days = intval($sec / (3600 * 24));
        $hours = intval(($sec % (3600 * 24)) / 3600);
        $minute = ceil(($sec % 3600) / 60);

        if ($days) {
            return $days . '天前';
        } elseif ($hours) {
            return $hours . '小时前';
        } elseif ($minute) {
            return $minute . '分钟前';
        } else {
            return '刚刚';
        }

    }
}


/**
 * 转换成小时分钟
 * @param array $arr
 * @author hejianyu
 */
function ConTime($msec)
{
    if (is_numeric($msec)) {

        $hours = intval($msec / 3600);
        $minute = ceil(($msec % 3600) / 60);
        $time = array(
            $hours ? $hours . '小时' : '', //小时数
            $minute ? $minute . '分钟' : ''//分钟数
        );
        return implode('', $time);
    }
}


/**
 * 将日期格式根据以下规律修改为不同显示样式
 * 小于1分钟 则显示多少秒前
 * 小于1小时，显示多少分钟前
 * 一天内，显示多少小时前
 * 3天内，显示前天22:23或昨天:12:23。
 * 超过3天，则显示完整日期。
 * @static
 * @param  $sorce_date 数据源日期 unix时间戳
 * @return void
 */
function getDateStyle($sorce_date)
{

    $nowTime = time();  //获取今天时间戳

    $timeHtml = ''; //返回文字格式
    $temp_time = 0;
    switch ($sorce_date) {

        //一分钟
        case ($sorce_date + 60) >= $nowTime:
            $temp_time = $nowTime - $sorce_date;
            $timeHtml = $temp_time . "秒前";
            break;

        //小时
        case ($sorce_date + 3600) >= $nowTime:
            $temp_time = date('i', $nowTime - $sorce_date);
            $timeHtml = $temp_time . "分钟前";
            break;

        //天
        case ($sorce_date + 3600 * 24) >= $nowTime:
            $temp_time = date('H', $nowTime) - date('H', $sorce_date);
            $timeHtml = $temp_time . '小时前';
            break;

        //昨天
        case ($sorce_date + 3600 * 24 * 2) >= $nowTime:
            $temp_time = date('H:i', $sorce_date);
            $timeHtml = '昨天' . $temp_time;
            break;

        //前天
        case ($sorce_date + 3600 * 24 * 3) >= $nowTime:
            $temp_time = date('H:i', $sorce_date);
            $timeHtml = '前天' . $temp_time;
            break;

        //3天前
        case ($sorce_date + 3600 * 24 * 4) >= $nowTime:
            $timeHtml = '3天前';
            break;

        default:
            $timeHtml = date('Y-m-d', $sorce_date);
            break;

    }
    return $timeHtml;

}

/**
 *  发送短信通知
 */

function  http_send_message($mobile,$str){
    $row=[];
    $url = 'http://smss.1tai.com/sms/server/send';
    $data = [
        'sign_name' => "TheONE钢琴盛典",
        'phone_number' => $mobile,
        'content' => $str
    ];
    $header = array(
        'Postman-Token:a714ad5f-dce5-a759-b883-e92e6220fe98',
        'Cache-Control:no-cache',
        'Content-Type:application/json'
    );
    $info = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if ($header) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $info);
    $res =  curl_exec($ch);
    if (curl_errno($ch)) {
        return curl_error($ch);
    }
    curl_close($ch);
    $row = json_decode($res, true);
    return $row['meta']['code'];
}
/**
 * 获取CURL请求
 * @param $url // 请求地址
 * @param string $type // 请求方式
 * @param string $res // 发送请求资源
 * @param string $header // 设置POST头部
 * @return mixed|string
 * @author jihaichuan
 */
function http_curl($url, $type = 'get', $res = '', $header = '')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if ($header) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    switch ($type) {
        case 'post':
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $res);
            break;
        case 'put':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $res);
            break;
    }
    $outopt = curl_exec($ch);
    if (curl_errno($ch)) {
        return curl_error($ch);
    }
    curl_close($ch);
    return json_decode($outopt, true);
}

/**
 * 判定是否为儿童(低于12岁)
 */
function getIDCardInfo($IDCard)
{

    if (strlen($IDCard) == 18) {
        $tyear = intval(substr($IDCard, 6, 4));
        $tmonth = intval(substr($IDCard, 10, 2));
        $tday = intval(substr($IDCard, 12, 2));
        if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
            $flag = 0;
        } elseif ($tmonth < 0 || $tmonth > 12) {
            $flag = 0;
        } elseif ($tday < 0 || $tday > 31) {
            $flag = 0;
        } else {
            $tdate = $tyear . "-" . $tmonth . "-" . $tday . " 00:00:00";
            if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 12 * 365 * 24 * 60 * 60) {
                $flag = 0;
            } else {
                $flag = 1;
            }
        }
    } elseif (strlen($IDCard) == 15) {
        $tyear = intval("19" . substr($IDCard, 6, 2));
        $tmonth = intval(substr($IDCard, 8, 2));
        $tday = intval(substr($IDCard, 10, 2));
        if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
            $flag = 0;
        } elseif ($tmonth < 0 || $tmonth > 12) {
            $flag = 0;
        } elseif ($tday < 0 || $tday > 31) {
            $flag = 0;
        } else {
            $tdate = $tyear . "-" . $tmonth . "-" . $tday . " 00:00:00";
            if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 12 * 365 * 24 * 60 * 60) {
                $flag = 0;
            } else {
                $flag = 1;
            }
        }
    }
    $result['error'] = 2;//0：未知错误，1：身份证格式错误，2：无错误
    $result['isAdult'] = $flag;//0标示成年，1标示未成年
    $result['birthday'] = $tdate;//生日日期
    return $result;
}

/**
 * 返回成功数据
 * @param $data
 * @author jihaichuan
 */
function json_success($data)
{
    header('HTTP/1.1 200 OK');
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data);
    exit;
}


/**
 * JSON 错误数据返回
 * @param $string
 * @author jihaichuan
 */
function json_fail($string)
{
    header('HTTP/1.1 500 Internal Server Error');
    header("Content-type: Application/json; charset=utf-8");
    if (is_array($string)) {
        echo json_encode($string);
        exit;
    } else {
        echo $string;
    }
    exit;
}

/**
 *
 * 获取星期几
 */

function get_week($date)
{
    //强制转换日期格式
    $date_str = date('Y-m-d', strtotime($date));

    //封装成数组
    $arr = explode("-", $date_str);

    //参数赋值
    //年
    $year = $arr[0];

    //月，输出2位整型，不够2位右对齐
    $month = sprintf('%02d', $arr[1]);

    //日，输出2位整型，不够2位右对齐
    $day = sprintf('%02d', $arr[2]);

    //时分秒默认赋值为0；
    $hour = $minute = $second = 0;

    //转换成时间戳
    $strap = mktime($hour, $minute, $second, $month, $day, $year);

    //获取数字型星期几
    $number_wk = date("w", $strap);

    //自定义星期数组
    $weekArr = array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");

    //获取数字对应的星期
    return $weekArr[$number_wk];
}

/**
 *
 * 数组排序
 */
function list_sort_by($list, $field, $sortby = 'asc')
{
    if (is_array($list)) {
        $refer = array();
        foreach ($list as $i => $data) {
            $refer[$i] = $data[$field];
        }
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc': // 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val) {
            $resultSet[] = $list[$key];
        }
        return $resultSet;
    }
    return false;
}

/**
 * 二位数组去除重复值
 * @param $arr 传入数组
 * @param $key 判断的key值
 * @return array
 */
function array_unset($arr, $key)
{   //$arr->传入数组   $key->判断的key值
    //建立一个目标数组
    $res = array();
    foreach ($arr as $value) {
        //查看有没有重复项
        if (isset($res[$value[$key]])) {
            //有：销毁
            unset($value[$key]);
        } else {
            $res[$value[$key]] = $value;
        }
    }
    return $res;
}

/**
 *
 *模板消息
 */
function sendTemplate($touser, $template_id, $form_id, $page, $data)
{

    $dataInfo = array(
        'touser' => $touser,
        'template_id' => $template_id,
        'form_id' => $form_id,
        'page' => $page,
        'data' => $data
    );
    $submitData = json_encode($dataInfo);
    //实例化表
    $token = Db('wx_token')->limit(1)->value('access_token');
    //获取模板消息
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $token;
    $info = http_curl($url, 'post', $submitData);

    return $info;
}

function download($file_url,$new_name=''){

    if(!isset($file_url)||trim($file_url)==''){
        echo '500';
    }
    if(!file_exists($file_url)){ //检查文件是否存在
        echo '404';
    }


    $file_name=basename($file_url);
    $file_type=explode('.',$file_url);
    $file_type=$file_type[count($file_type)-1];
    $file_name=trim($new_name=='')?$file_name:urlencode($new_name);
    $file_type=fopen($file_url,'r'); //打开文件
    //输入文件标签
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");
    header("Accept-Length: ".filesize($file_url));
    header("Content-Disposition: attachment; filename=".$file_name);
    //输出文件内容
    echo fread($file_type,filesize($file_url));

    fclose($file_type);
}